package com.jlgp.exam.topic250512.demo2;

/**
 * @ Description: 排序找数字
 * 从升序数组中找出两个数，使它们的和等于指定值，要求时间复杂度为O(n)
 * @ BelongsProject: code
 * @ Author: G攀
 * @ CreateTime: 2025-05-12  01:09
 * @ Version: 1.0
 */
public class SortForSum {
    /*解题思路
    使用双指针法：
    设指针 low 指向数组开头，high 指向数组末尾。
    计算两指针指向元素的和：
    若和等于指定值，找到目标。
    若和小于指定值，low 右移（增大和）。
    若和大于指定值，high 左移（减小和）。
    循环直至找到结果或指针相遇。*/

    public static Result find(int[] data, int sum) {
        int low = 0;
        int high = data.length - 1;
        while (low < high) {
            int currentSum = data[low] + data[high];
            if (currentSum == sum) {
                Result rs = new Result();
                rs.setNum1(data[low]);
                rs.setNum2(data[high]);
                rs.setSuccess(true);
                return rs;
            } else if (currentSum < sum) {
                low++;
            } else {
                high--;
            }
        }
        return null;
    }

    public static void main(String[] args) {
        int[] data = {1, 2, 4, 7, 12, 15};
        int sum = 14;
        Result rs = find(data, sum);
        if (rs != null) {
            System.out.println("found:" + rs.isSuccess() + "," + rs.getNum1() + "," + rs.getNum2());
        } else {
            System.out.println("found: false");
        }
    }
}


class Result {
    private int num1;
    private int num2;
    private boolean success;

    public int getNum1() {
        return num1;
    }

    public void setNum1(int num1) {
        this.num1 = num1;
    }

    public int getNum2() {
        return num2;
    }

    public void setNum2(int num2) {
        this.num2 = num2;
    }

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }
}
